﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using BusinessCache;
using BusinessEntity;
using BusinessEntity.Warning;
using BusinessRule;
using BusinessRule.Organization;
using learun.util;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Nacos.AspNetCore;
using Newtonsoft.Json.Linq;
using NLog;

namespace Productive.Assets
{
    [TypeFilter(typeof(ExceptionFilter))]
    [ApiController]
    [Route("Productive/[controller]/[action]")]
    public class MvcControllerBase : Controller
    {
        //添加NLog
        internal Logger _logger = LogManager.GetCurrentClassLogger();
        public MvcControllerBase()
        {

        }

        private readonly INacosServerManager _serverManager;
        public MvcControllerBase(INacosServerManager serverManager)
        {
            _serverManager = serverManager;
            
        }

     

        #region 盘古审批状态

        //////导出  审批
        //投资计划id   id
        //项目 id    id
        //概算批次 id    id
        //概算列表 xmid   
        //采购 dxid  id
        //招标 id   zbid 
        //合同 dxid  id
        //付款月计划 id  id  View_ProFKYJHLists
        //竣工 tid   id
        //结算 tid   id
        //归档 xmid  id

        //盘古列表返回
        internal JavaApi.panguData GetPanGudData(JavaApi.SPSDataItem spstatus, string yspstatus)
        {
            JavaApi.panguData panguData = new JavaApi.panguData();
            if (null != spstatus)
            {
                panguData.taskId = spstatus.taskId;
                panguData.instanceId = spstatus.processInstanceId;
                panguData.reviewStatus = yspstatus;
                panguData.approvalAuth = spstatus.approvalAuth;
                panguData.cancelAuth = spstatus.cancelAuth;
                panguData.restartAuth = spstatus.restartAuth;
                return panguData;
            }
            else
            {
                //dynamic panguData = new ExpandoObject();
                panguData.reviewStatus = yspstatus;
                return panguData;
            }
        }

        #endregion

        #region 获取权限depid 和 服务发现
        protected async Task<string> GetDicJavaAPI(string typename, string tname)
        {
            string stradmin = ConfigHelper.GetAppSettings("ServerOp:SerAdmin");

            List<JavaApi.DataItemDIC> list = await GetDicJavaAPI2(typename, stradmin);

            JavaApi.DataItemDIC dic = list.Find(l => {
                return l.value == tname;
            });

            if (null != list)
            {
                return dic.code;
            }
            else {
               return "QT";
            }
        }



        protected async Task<List<JavaApi.DataItemDIC>> GetDicJavaAPI2(string tname, string stradmin)
        {
            //string stradmin = ConfigHelper.GetAppSettings("ServerOp:SerAdmin");

            List<JavaApi.DataItemDIC> list = await JavaApi.GetDicJavaAPI(tname, await GetICApiInfo(stradmin));

            return list;
        }

        protected async Task<(string, string)> GetICApiInfo(string serviceName = "ic-business")
        {
            string strUrl = await GetIcUrl(serviceName);
            string strAuthorization = GetAuthorization();
            return (strUrl, strAuthorization);
        }

        //protected async Task<string> GetDepId(string serviceName = "ic-upms-biz")
        //{
        //    string strUrl = await GetIcUrl(serviceName);
        //    string strAuthorization = GetAuthorization();

        //    //if (string.IsNullOrEmpty(strUrl))
        //    //{
        //    //    throw new Exception("ic-upms-biz服务发现没有节点");
        //    //}
        //    //if (string.IsNullOrEmpty(strAuthorization))
        //    //{
        //    //    throw new Exception("权限校验失败，Token过期或无效");
        //    //}
        //    return await JavaApi.GetDepId("", strUrl, strAuthorization);
        //}

        protected async Task<string> GetDepId(string permission = "project_permission", string serviceName = "ic-upms-biz")// permission暂时写死
        {
            string strUrl = await GetIcUrl(serviceName);
            string strAuthorization = GetAuthorization();

            //if (string.IsNullOrEmpty(strUrl))
            //{
            //    throw new Exception("ic-upms-biz服务发现没有节点");
            //}
            //if (string.IsNullOrEmpty(strAuthorization))
            //{
            //    throw new Exception("权限校验失败，Token过期或无效");
            //}

            return await JavaApi.GetDepId(permission, strUrl, strAuthorization);
        }

        protected async Task<string> Getorg(string permission = "regulation_permission")// permission暂时写死
        {
            
            string strAuthorization = GetAuthorization();

            //if (string.IsNullOrEmpty(strUrl))
            //{
            //    throw new Exception("ic-upms-biz服务发现没有节点");
            //}
            //if (string.IsNullOrEmpty(strAuthorization))
            //{
            //    throw new Exception("权限校验失败，Token过期或无效");
            //}

            return await JavaApi.GetOrg(permission, ConfigHelper.GetConfig().IMUrl, strAuthorization);
        }
        //protected async Task<List<JavaApi.DataItem>> GetDepInfo(string serviceName = "ic-upms-biz")
        //{
        //    string strUrl = await GetIcUrl(serviceName);
        //    string strAuthorization = GetAuthorization();

        //    //if (string.IsNullOrEmpty(strUrl))
        //    //{
        //    //    throw new Exception("ic-upms-biz服务发现没有节点");
        //    //}
        //    //if (string.IsNullOrEmpty(strAuthorization))
        //    //{
        //    //    throw new Exception("权限校验失败，Token过期或无效");
        //    //}
        //    //List<DataItem>
        //    return (await JavaApi.GetDepInfo(strUrl, strAuthorization));
        //}

        protected async Task<JavaApi.DataItem> GetDepInfoSig(string dwid, string permission, string serviceName = "ic-upms-biz")
        {
            string strUrl = await GetIcUrl(serviceName);
            string strAuthorization = GetAuthorization();

            return (await JavaApi.GetDepInfoSig(dwid, permission, strUrl, strAuthorization));
        }

        protected async Task<JavaApi.DataItem> GetDepIDInfoSig(string dwmc, string permission= "project_permission", string serviceName = "ic-upms-biz")
        {
            string strUrl = await GetIcUrl(serviceName);
            string strAuthorization = GetAuthorization();

            return (await JavaApi.GetDepIDInfoSig(dwmc, permission, strUrl, strAuthorization));
        }

        protected async Task<List<JavaApi.DataItem>> GetDepInfoList(string permission = "project_permission", string serviceName = "ic-upms-biz")
        {
            string strUrl = await GetIcUrl(serviceName);
            string strAuthorization = GetAuthorization();

            return (await JavaApi.GetDepInfoList(permission, strUrl, strAuthorization));
        }


        //protected async Task<JavaApi.DataItem> GetDepInfo(string permission = "project_permission", string serviceName = "ic-upms-biz")
        //{
        //    string strUrl = await GetIcUrl(serviceName);
        //    string strAuthorization = GetAuthorization();

        //    return (await JavaApi.GetDepIDInfoSig(dwmc, permission, strUrl, strAuthorization));
        //}

        protected async Task<IEnumerable<dynamic>> GetDepInfoTree(string strlx, string dxmc,string permission, string serviceName = "ic-upms-biz")
        {
            string strUrl = await GetIcUrl(serviceName);
            string strAuthorization = GetAuthorization();

            return (await JavaApi.GetDepInfoTree(strlx, dxmc, permission, strUrl, strAuthorization));
        }

        protected async Task<string> GetIcUrl(string serviceName)
        {
            var baseUrl = await _serverManager.GetServerAsync(serviceName);//.GetAwaiter().GetResult()

            return baseUrl;
        }



        #endregion

        #region 获取基础信息
        private AUserEntity userInfo;
        /// <summary>
        /// 获取当前用户信息
        /// </summary>
        /// <param name="userId">用户id</param>
        /// <returns></returns>
        protected async Task<AUserEntity> CurrentUser(string userId = null)
        {

            //var userBLL = IocManager.Instance.GetService<UserIBLL>();
            //if (string.IsNullOrEmpty(userId))
            //{
            //    if (userInfo == null)
            //    {
            //        userInfo = await userBLL.GetEntity();
            //    }
            //    return userInfo;
            //}
            //else
            //{
            //    return await userBLL.GetEntity(userId);
            //}

            if (string.IsNullOrEmpty(userId))
            {
                if (userInfo == null)
                {
                    userInfo = await UserRule.GetEntity();
                }
                return userInfo;
            }
            else
            {
                return await UserRule.GetEntity(userId);
            }
        }

        ///// <summary>
        ///// 获取编码
        ///// </summary>
        ///// <param name="code">编码规则编码</param>
        ///// <returns></returns>
        //protected Task<string> GetRuleCode(string code)
        //{
        //    var codeRuleIBLL = IocManager.Instance.GetService<CodeRuleIBLL>();
        //    return codeRuleIBLL.GetBillCode(code);
        //}
        ///// <summary>
        ///// 占用编码
        ///// </summary>
        ///// <param name="code">编码规则编码</param>
        ///// <returns></returns>
        //protected async Task UseRuleSeed(string code)
        //{
        //    var codeRuleIBLL = IocManager.Instance.GetService<CodeRuleIBLL>();
        //    await codeRuleIBLL.UseRuleSeed(code);
        //}

        //public dynamic CrtUser()//string info
        //{
        //    dynamic d = new ExpandoObject();
        //    d.userId = ContextHelper.GetItem("userId");
        //    d.deptId = ContextHelper.GetItem("deptId");
        //    d.deptName = ContextHelper.GetItem("deptName");
        //    return d;

        //    //return ContextHelper.GetItem(info) == null ? "" : ContextHelper.GetItem(info) as string;
        //}

        /// <summary>
        /// 获取登录者用户名称
        /// </summary>
        /// <returns></returns>
        protected string GetUserName()
        {
            return ContextHelper.GetItem("userName") as string;
        }
        /// <summary>
        /// 获取登录者用户Id
        /// </summary>
        /// <returns></returns>
        protected string GetUserId()
        {
            return ContextHelper.GetItem("userId") == null ? "1" : ContextHelper.GetItem("userId") as string;
        }
        /// <summary>
        /// 获取登录者用户账号
        /// </summary>
        /// <returns></returns>
        protected string GetUserAccount()
        {
            return ContextHelper.GetItem("account") as string;
        }

        protected string GetUserDeptid()
        {
            return ContextHelper.GetItem("deptId") as string;
        }

        protected string GetUserDeptName()
        {
            return ContextHelper.GetItem("deptName") as string;
        }

        protected string GetAuthorization()
        {
            var authorization = Request.Headers["Authorization"];
            return authorization.ToString().Replace("bearer ", "");
        }

        /// <summary>
        /// 返回用户编号
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        protected string GetTokenUserID()
        {
            string token = Request.Headers["Authorization"].ToString().Replace("bearer ", "");
            RedisCache redis = new RedisCache();
            return redis.StringGet("review:login:token:" + token);
        }



        protected string GetUserInfo(string userid)
        {
            string json = "";

            string url = ConfigHelper.GetConfig().IMUrl + "/user/";
            string body = "id=" + userid;
            //json = HttpMethods.Get(url + "?" + body).GetAwaiter().GetResult();
            json = JavaApi.HttpPost(url, body);
            return json;
        }

        #endregion 

        #region 请求响应
        /// <summary>
        /// 返回成功数据
        /// </summary>
        /// <param name="data">数据</param>
        /// <returns></returns>
        protected virtual IActionResult Success(object data)
        {
            return Content(new ResParameter { code = ResponseCode.success, message = "响应成功", data = data }.ToJson());
        }
        /// <summary>
        /// 返回成功数据
        /// </summary>
        /// <param name="data">数据</param>
        /// <returns></returns>
        protected virtual IActionResult SuccessCenter(object data, string status)
        {
            if (status == "true")
            {
                return Content(new ReturnParameter { status = status, code = ResponseCode.success, message = "响应成功", data = data }.ToJson());
            }
            else
            {
                return Content(new ReturnParameter { status = status, code = ResponseCode.fail, message = "响应失败", data = data }.ToJson());
            }
        }
        /// <summary>
        /// 返回成功数据
        /// </summary>
        /// <param name="data">数据</param>
        /// <returns></returns>
        protected virtual IActionResult Success(object data, bool isLower)
        {
            if (isLower)
            {
                return Content(new ResParameter { code = ResponseCode.success, message = "响应成功", data = data }.ToJson().ToLower());
            }
            else
            {
                return Content(new ResParameter { code = ResponseCode.success, message = "响应成功", data = data }.ToJson());
            }
        }
       
        /// <summary>
        /// 返回成功消息
        /// </summary>
        /// <param name="info">信息</param>
        /// <param name="data">数据</param>
        /// <returns></returns>
        protected virtual IActionResult Success(string info, object data)
        {
            return Content(new ResParameter { code = ResponseCode.success, message = info, data = data }.ToJson());
        }
        /// <summary>
        /// 返回成功数据
        /// </summary>
        /// <param name="info">信息</param>
        /// <returns></returns>
        protected virtual IActionResult SuccessInfo(string info)
        {
            return Content(new ResParameter { code = ResponseCode.success, message = info }.ToJson());
        }


        /// <summary>
        /// 返回失败消息
        /// </summary>
        /// <param name="info">消息</param>
        /// <returns></returns>
        protected virtual IActionResult Fail(string info)
        {
            //_logger.Error(Request.RouteValues["controller"].ToString() + "/" + Request.RouteValues["action"] + ":" + info);
            return Content(new ResParameter { code = ResponseCode.fail, message = info }.ToJson());
        }

        /// <summary>
        /// 返回失败消息
        /// </summary>
        /// <param name="info">消息</param>
        /// <returns></returns>
        protected virtual IActionResult Failnologin(string info)
        {
            return Content(new ResParameter { code = ResponseCode.nologin, message = info }.ToJson());
        }
        #endregion

        /// <summary>
        /// 获取cookies
        /// </summary>
        /// <param name="key">键</param>
        /// <returns>返回对应的值</returns>
        protected string GetCookies(string key)
        {
            HttpContext.Request.Cookies.TryGetValue(key, out string value);
            if (string.IsNullOrEmpty(value))
                value = string.Empty;
            return value;
        }

        protected string GetJavaWarning()
        {
            string json = "";
            string url = ConfigHelper.GetConfig().ICWarning;
            string strAuthorization = GetAuthorization();
            json = GetWarning(url, strAuthorization).ToString();
            return json;
        }

        #region "获取预警信息"
        protected async Task<string> GetWarning(string baseUrl, string strAuthorization)
        {
            try
            {
                
              
                var url = baseUrl;

                using (HttpClient client = new HttpClient())
                {
                    string clientInfo = "test:test";
                    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(clientInfo);
                    clientInfo = Convert.ToBase64String(bytes, Base64FormattingOptions.None);

                    //"Basic " +
                    client.DefaultRequestHeaders.Add("Authorization", "bearer " + strAuthorization);//"Basic " + clientInfo


                    //url = url.Replace("172.31.162.64:4000", "118.190.140.38:4000");
                    //url = GetIpAddress(baseUrl) + permission;

                    var response = await client.GetAsync(url);

                    //获取请求到数据，并转化为字符串
                    var result = response.Content.ReadAsStringAsync().Result;

                    //List<JavaWarning> ja = new List<JavaWarning>();

                    //JObject jb = JObject.Parse(result);
                    //if (jb["code"].ToString() == "200")
                    //{
                    //    ja = ExtensionsJson.ToList<JavaWarning>(jb["data"].ToString());
                    //}

                    return result;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        #endregion
    }
}